package com.estore.network;

import com.estore.model.Product;
import com.estore.service.ProductSorters;

import java.io.*;
import java.net.Socket;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

/**
 * 电子商城客户端 - 重构为C/S架构
 * 通过Socket连接服务器，发送请求并接收数据
 */
public class EStoreClient {
    //服务器配置
    private static final String SERVER_HOST = "localhost";
    private static final int SERVER_PORT = 8888;

    //网络连接相关
    private Socket socket;
    private ObjectInputStream inputStream;
    private ObjectOutputStream outputStream;

    //本地数据
    private final Map<String, Integer> shoppingCart = new HashMap<>();
    private final Scanner scanner = new Scanner(System.in);

    public void start() {
        System.out.println("欢迎来到电子商城客户端！");

        while (true) {
            showMainMenu();
            String input = scanner.nextLine().trim();

            if (input.isEmpty()) {
                System.out.println("请输入有效的选择！");
                continue;
            }

            try {
                int choice = Integer.parseInt(input);

                switch (choice) {
                    case 1:
                        browseProducts(null, "（默认排序）");
                        break;
                    case 2:
                        showSortedProducts();
                        break;
                    case 3:
                        searchProducts();
                        break;
                    case 4:
                        searchProductsByTag();
                        break;
                    case 5:
                        addToCart();
                        break;
                    case 6:
                        viewCart();
                        break;
                    case 7:
                        showProductsWithTags(); // 新增：显示带标签的商品
                        break;
                    case 8:
                        saveDataToServer();
                        System.out.println("感谢使用，再见！");
                        return;
                    case 9:
                        adminBackupMenu();
                        break;
                    default:
                        System.out.println("无效的选项，请重新输入！");
                }
            } catch (NumberFormatException e) {
                System.out.println("请输入有效的数字！");
            }
        }
    }
    /**
     * 连接到服务器
     */
    private boolean connectToServer() {
        try {
            if (socket == null || socket.isClosed()) {
                socket = new Socket(SERVER_HOST, SERVER_PORT);
                outputStream = new ObjectOutputStream(socket.getOutputStream());
                inputStream = new ObjectInputStream(socket.getInputStream());
                System.out.println("已连接到服务器: " + SERVER_HOST + ":" + SERVER_PORT);
            }
            return true;
        } catch (IOException e) {
            System.err.println("连接服务器失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 关闭连接
     */
    private void closeConnection() {
        try {
            if (outputStream != null) outputStream.close();
            if (inputStream != null) inputStream.close();
            if (socket != null && !socket.isClosed()) {
                socket.close();
            }
        } catch (IOException e) {
            System.err.println("关闭连接时出错: " + e.getMessage());
        }
    }

    /**
     * 发送请求到服务器并获取响应
     */
    private Object sendRequestToServer(String request, Object... parameters) {
        if (!connectToServer()) {
            return null;
        }

        try {
            // 发送请求
            outputStream.writeObject(request);
            outputStream.flush();

            // 发送参数
            for (Object param : parameters) {
                outputStream.writeObject(param);
                outputStream.flush();
            }

            // 接收响应
            return inputStream.readObject();

        } catch (IOException | ClassNotFoundException e) {
            System.err.println("与服务器通信失败: " + e.getMessage());
            closeConnection(); // 发生错误时关闭连接
            return null;
        }
    }

    /**
     * 浏览商品 - 通过Socket连接服务器获取数据
     */
    private void browseProducts(Comparator<Product> comparator, String sortDescription) {
        System.out.println("\n--- 商品列表 " + sortDescription + " ---");

        // 通过Socket连接服务器获取商品数据
        Object response = sendRequestToServer("GET_ALL_PRODUCTS");

        if (response instanceof List) {
            @SuppressWarnings("unchecked")
            List<Product> products = (List<Product>) response;

            if (products.isEmpty()) {
                System.out.println("商店里还没有商品。");
                waitForEnter();
                return;
            }
            // 创建商品列表的副本进行排序
            List<Product> displayProducts = new java.util.ArrayList<>(products);

            // 排序处理
            if (comparator != null) {
                displayProducts.sort(comparator);
            } else {
                java.util.Collections.sort(displayProducts);
            }

            // 显示商品列表
            for (int i = 0; i < displayProducts.size(); i++) {
                Product product = displayProducts.get(i);
                System.out.printf("%d. %s\n", i + 1, product);
            }
        } else {
            System.out.println("获取商品数据失败！");
        }

        waitForEnter();
    }

    /**
     * 显示排序选项
     */
    private void showSortedProducts() {
        System.out.println("\n========== 选择排序方式 ==========");
        System.out.println("1. 按价格从低到高");
        System.out.println("2. 按价格从高到低");
        System.out.println("3. 按库存从多到少");
        System.out.println("4. 按商品ID排序（默认）");
        System.out.println("5. 返回主菜单");
        System.out.println("=================================");
        System.out.print("请选择排序方式 (1-5): ");

        String input = scanner.nextLine().trim();
        if (input.isEmpty()) return;

        try {
            int choice = Integer.parseInt(input);
            Comparator<Product> comparator = null;
            String sortDescription;

            switch (choice) {
                case 1:
                    comparator = ProductSorters.BY_PRICE_ASC;
                    sortDescription = "（按价格从低到高）";
                    break;
                case 2:
                    comparator = ProductSorters.BY_PRICE_DESC;
                    sortDescription = "（按价格从高到低）";
                    break;
                case 3:
                    comparator = ProductSorters.BY_STOCK_DESC;
                    sortDescription = "（按库存从多到少）";
                    break;
                case 4:
                    sortDescription = "（按ID排序）";
                    break;
                case 5:
                    return;
                default:
                    System.out.println("无效选择，使用默认排序！");
                    sortDescription = "（默认排序）";
            }

            browseProducts(comparator, sortDescription);
        } catch (NumberFormatException e) {
            System.out.println("请输入有效的数字！");
        }
    }

    /**
     * 搜索商品
     */
    private void searchProducts() {
        System.out.print("\n请输入要搜索的商品名称关键词: ");
        String keyword = scanner.nextLine().trim();

        if (keyword.isEmpty()) {
            System.out.println("搜索关键词不能为空！");
            waitForEnter();
            return;
        }

        // 通过Socket连接服务器搜索商品
        Object response = sendRequestToServer("SEARCH_PRODUCTS_BY_NAME", keyword);

        if (response instanceof List) {
            @SuppressWarnings("unchecked")
            List<Product> searchResults = (List<Product>) response;

            if (searchResults.isEmpty()) {
                System.out.println("没有找到包含 \"" + keyword + "\" 的商品。");
            } else {
                System.out.println("\n--- 搜索结果（共 " + searchResults.size() + " 件商品）---");
                for (int i = 0; i < searchResults.size(); i++) {
                    Product product = searchResults.get(i);
                    System.out.printf("%d. %s\n", i + 1, product);
                }
            }
        } else {
            System.out.println("搜索商品失败！");
        }

        waitForEnter();
    }

    /**
     * 按标签搜索商品
     */
    private void searchProductsByTag() {
        System.out.println("\n可用的标签示例: 编程, 畅销, 热门, 小说, 推荐, 健康, 生活");
        System.out.print("请输入要搜索的标签: ");
        String tag = scanner.nextLine().trim();

        if (tag.isEmpty()) {
            System.out.println("标签不能为空！");
            waitForEnter();
            return;
        }

        // 通过Socket连接服务器搜索商品
        Object response = sendRequestToServer("SEARCH_PRODUCTS_BY_TAG", tag);

        if (response instanceof List) {
            @SuppressWarnings("unchecked")
            List<Product> searchResults = (List<Product>) response;

            if (searchResults.isEmpty()) {
                System.out.println("没有找到包含标签 \"" + tag + "\" 的商品。");
            } else {
                System.out.println("\n--- 标签 \"" + tag + "\" 搜索结果（共 " + searchResults.size() + " 件商品）---");
                for (int i = 0; i < searchResults.size(); i++) {
                    Product product = searchResults.get(i);
                    System.out.printf("%d. %s\n", i + 1, product);
                }
            }
        } else {
            System.out.println("按标签搜索失败！");
        }

        waitForEnter();
    }

    /**
     * 显示所有带标签的商品
     */
    private void showProductsWithTags() {
        System.out.println("\n--- 带标签的商品列表 ---");

        // 获取所有商品
        Object response = sendRequestToServer("GET_ALL_PRODUCTS");

        if (response instanceof List) {
            @SuppressWarnings("unchecked")
            List<Product> allProducts = (List<Product>) response;

            List<Product> productsWithTags = allProducts.stream()
                    .filter(product -> product.getTags() != null && !product.getTags().isEmpty())
                    .toList();

            if (productsWithTags.isEmpty()) {
                System.out.println("目前没有带标签的商品。");
            } else {
                System.out.println("共找到 " + productsWithTags.size() + " 件带标签的商品:");
                for (int i = 0; i < productsWithTags.size(); i++) {
                    Product product = productsWithTags.get(i);
                    System.out.printf("%d. %s\n", i + 1, product);
                }

                // 显示标签统计
                System.out.println("\n--- 标签统计 ---");
                Map<String, Integer> tagCount = new HashMap<>();
                for (Product product : productsWithTags) {
                    for (String tag : product.getTags()) {
                        tagCount.put(tag, tagCount.getOrDefault(tag, 0) + 1);
                    }
                }

                for (Map.Entry<String, Integer> entry : tagCount.entrySet()) {
                    System.out.printf("标签 '%s': %d 件商品\n", entry.getKey(), entry.getValue());
                }
            }
        } else {
            System.out.println("获取商品数据失败！");
        }

        waitForEnter();
    }

    /**
     * 添加到购物车
     */
    private void addToCart() {
        // 先获取有库存的商品
        Object response = sendRequestToServer("GET_AVAILABLE_PRODUCTS");

        if (!(response instanceof List)) {
            System.out.println("获取商品数据失败！");
            waitForEnter();
            return;
        }

        @SuppressWarnings("unchecked")
        List<Product> availableProducts = (List<Product>) response;

        if (availableProducts.isEmpty()) {
            System.out.println("目前没有可购买的商品，所有商品都已售罄！");
            waitForEnter();
            return;
        }

        System.out.println("\n--- 可购买的商品 ---");
        for (int i = 0; i < availableProducts.size(); i++) {
            Product product = availableProducts.get(i);
            System.out.printf("%d. %s\n", i + 1, product);
        }

        System.out.print("\n请输入要添加的商品ID: ");
        String productId = scanner.nextLine().trim().toLowerCase();

        // 通过服务器验证商品存在性
        Object productResponse = sendRequestToServer("GET_PRODUCT_BY_ID", productId);

        if (productResponse instanceof Product) {
            Product product = (Product) productResponse;

            if (product.getStock() <= 0) {
                System.out.println("抱歉，该商品已售罄。");
                waitForEnter();
                return;
            }

            System.out.print("请输入购买数量 (当前库存: " + product.getStock() + "): ");
            String quantityInput = scanner.nextLine().trim();

            if (quantityInput.isEmpty()) {
                System.out.println("购买数量不能为空！");
                waitForEnter();
                return;
            }

            try {
                int quantity = Integer.parseInt(quantityInput);

                if (quantity <= 0) {
                    System.out.println("错误：购买数量必须为正数！");
                } else if (quantity > product.getStock()) {
                    System.out.println("错误：库存不足！当前库存为 " + product.getStock());
                } else {
                    // 将商品加入购物车，如果已存在则累加数量
                    int currentQuantity = shoppingCart.getOrDefault(productId, 0);
                    shoppingCart.put(productId, currentQuantity + quantity);
                    System.out.println("成功将 '" + product.getName() + "' × " + quantity + " 添加到购物车！");
                }
            } catch (NumberFormatException e) {
                System.out.println("错误：请输入有效的数字！");
            }
        } else {
            System.out.println("错误：找不到该商品！");
        }

        waitForEnter();
    }

    /**
     * 查看购物车
     */
    private void viewCart() {
        System.out.println("\n--- 我的购物车 ---");

        if (shoppingCart.isEmpty()) {
            System.out.println("购物车是空的，快去逛逛吧！");
            waitForEnter();
            return;
        }

        double total = 0.0;
        int itemCount = 0;

        for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
            String productId = entry.getKey();
            Integer quantity = entry.getValue();

            // 通过服务器获取商品信息
            Object response = sendRequestToServer("GET_PRODUCT_BY_ID", productId);

            if (response instanceof Product) {
                Product product = (Product) response;
                double subtotal = product.getPrice() * quantity;
                System.out.printf("商品: %-20s | 单价: ¥%-8.2f | 数量: %-3d | 小计: ¥%.2f\n",
                        product.getName(), product.getPrice(), quantity, subtotal);
                total += subtotal;
                itemCount += quantity;
            }
        }

        System.out.println("------------------------------------");
        System.out.printf("商品种类: %d 件, 商品总数: %d 件, 总计: ¥%.2f\n",
                shoppingCart.size(), itemCount, total);

        waitForEnter();
    }

    /**
     * 保存数据到服务器
     */
    private void saveDataToServer() {
        Object response = sendRequestToServer("SAVE_DATA");
        if (response instanceof String) {
            System.out.println(response);
        }
    }

    /**
     * 管理员备份菜单
     */
    private void adminBackupMenu() {
        System.out.println("\n=== 管理员数据备份菜单 ===");
        System.out.println("1. 备份当前数据");
        System.out.println("2. 从备份恢复数据");
        System.out.println("3. 查看备份信息");
        System.out.println("4. 返回主菜单");
        System.out.print("请选择操作 (1-4): ");

        String input = scanner.nextLine().trim();

        switch (input) {
            case "1":
                backupData();
                break;
            case "2":
                restoreFromBackup();
                break;
            case "3":
                showBackupInfo();
                break;
            case "4":
                return;
            default:
                System.out.println("无效的选择！");
        }

        waitForEnter();
    }

    /**
     * 备份数据
     */
    private void backupData() {
        System.out.println("\n--- 数据备份 ---");

        // 先保存当前数据
        saveDataToServer();

        // 执行备份
        Object response = sendRequestToServer("BACKUP_DATA");
        if (response instanceof String) {
            System.out.println(response);
        }
    }

    /**
     * 从备份恢复数据
     */
    private void restoreFromBackup() {
        System.out.println("\n--- 从备份恢复数据 ---");

        System.out.println("警告：此操作将用备份文件覆盖当前数据！");
        System.out.print("确认恢复吗？(y/N): ");
        String confirm = scanner.nextLine().trim();

        if ("y".equalsIgnoreCase(confirm) || "yes".equalsIgnoreCase(confirm)) {
            // 注意：这里需要服务器端实现恢复功能
            System.out.println("恢复功能需要在服务器端实现");
        } else {
            System.out.println("已取消恢复操作。");
        }
    }

    /**
     * 显示备份信息
     */
    private void showBackupInfo() {
        System.out.println("\n--- 备份信息 ---");
        // 注意：这里需要服务器端实现获取备份信息的功能
        System.out.println("备份信息功能需要在服务器端实现");
    }

    /**
     * 显示主菜单
     */

    private void showMainMenu() {
        System.out.println("\n========== 电子商城主菜单 ==========");
        System.out.println("1. 浏览所有商品（默认排序）");
        System.out.println("2. 自定义排序浏览商品");
        System.out.println("3. 按名称搜索商品");
        System.out.println("4. 按标签搜索商品"); // 新增菜单项
        System.out.println("5. 添加商品到购物车");
        System.out.println("6. 查看购物车");
        System.out.println("7. 查看带标签的商品"); // 新增菜单项
        System.out.println("8. 退出系统");
        System.out.println("====================================");
        System.out.print("请输入您的选择 (1-8): ");
    }
    /**
     * 等待用户按回车键继续
     */
    private void waitForEnter() {
        System.out.print("\n按回车键继续...");
        scanner.nextLine();
    }

    /**
     * 主方法
     */
    public static void main(String[] args) {
        EStoreClient client = new EStoreClient();
        client.start();
    }
}